package web.comment;

import bean.User;
import entity.TypeEntity;
import entity.UserEntity;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = {"/dao/login/local"})
public class login_local extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Query query = em.createNativeQuery("select uid from UserEntity where name = ?");
        query.setParameter(1, username);
        List list = query.getResultList();
        if(list.size()==0){
            request.getSession().setAttribute("error", "账号或者密码错误！");
            response.sendRedirect("http://localhost:8080/user/login.jsp");
        }
        UserEntity userEntity = em.find(UserEntity.class,Integer.parseInt(""+list.get(0)));
        if(userEntity!=null) {
            User user = new User();
            user.setEmail(userEntity.getEmail());
            user.setName(userEntity.getName());
            user.setPhone(userEntity.getPhone());
            user.setUid(userEntity.getUid()+"");
            user.setVip(userEntity.getVip());
            if (user.getPhone().equals(password)) {
                request.getSession().setAttribute("user", user);
                response.sendRedirect("http://localhost:8080/user/index.html");
            } else {
                request.getSession().setAttribute("error", "账号或者密码错误！");
                response.sendRedirect("http://localhost:8080/user/login.jsp");
            }
        }else {
            request.getSession().setAttribute("error", "账号或者密码错误！");
            response.sendRedirect("http://localhost:8080/user/login.jsp");
        }
    }
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException, ServletException {
        doGet(request,response);
    }
}